package server.storage;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class PrivateMessagesStorage {

    private final DataOutputStream oos;

    public PrivateMessagesStorage(String path) throws IOException {
        File file = new File(path);
        if (!file.exists()) {
            file.createNewFile();
        }
        oos = new DataOutputStream(new FileOutputStream(file, true));

    }

    public boolean saveMessage(String from, String to, String message) {
        try {
            oos.writeUTF(from);
            oos.writeUTF(to);
            oos.writeUTF(message);
            oos.flush();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    public List<String> getPrivate(String file, String username, int maxNumber) throws FileNotFoundException {
        int download = 0;
        ArrayList<String> result = new ArrayList<>();
        try (DataInputStream ois = new DataInputStream(new FileInputStream(file))) {
            while ((ois.available() > 0) && (download < maxNumber)) {
                String from = ois.readUTF();
                String to = ois.readUTF();
                String message = ois.readUTF();
                if (username.equals(from) || username.equals(to))
                    result.add(message);
                download++;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }


    public void close() {
        try {
            oos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
